<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="文件类型" prop="fileType">
        <el-select v-model="queryParams.fileType" placeholder="选择类型">
          <el-option
            v-for="item in this.dict.type.mc_file_type"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="发布时间" prop="checkInfoTime">
        <el-date-picker
          v-model="dateRange"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
        >搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
        >重置</el-button>
      </el-form-item>
      <el-form-item style="position: absolute; right: 25px">
        <el-button
          type="danger"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['product:add']"
        >新增</el-button>
      </el-form-item>
    </el-form>

    <el-table :data="tableData" style="width: 100%">
      <el-table-column prop="title" label="标题"
                       :min-width="120"
                       :max-width="600"> </el-table-column>
      <el-table-column prop="fileType" label="文件类型" width="230">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.mc_file_type"
            :value="scope.row.fileType"
          />
        </template>
      </el-table-column>
      <el-table-column prop="nickName" label="发布者" width="230"> </el-table-column>
      <el-table-column prop="createTime" label="上传时间" width="260"> </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        width="180"
      >
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.fileType === 10"
            size="mini"
            type="text"
            icon="el-icon-search"
            @click="handleWatch(scope.row)"
          >查看</el-button>
          <el-button
            v-if="shouldShowEditButton(scope.row)"
            size="mini"
            type="text"
            icon="el-icon-search"
            @click="handleDownload(scope.row)"
          >下载</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['device:document:del']"
          >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total > 0"
      :total="total"
      :page-sizes="[50,  100]"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 新增 -->
    <el-dialog title="添加资料" :visible.sync="open" width="30%" append-to-body v-loading="loading">
      <el-form ref="form" :model="form" :rules="rules" label-width="auto">
        <el-row>
          <el-col :span="24">
            <el-form-item label="标题" prop="title">
              <el-input v-model="form.title" placeholder="标题不能重复。自动去除空格。"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="文件说明" prop="fileDesc">
              <el-input
                type="textarea"
                :rows="2"
                v-model="form.fileDesc"
                controls-position="right"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="是否公开" prop="fileType">
              <el-select v-model="form.isOpen" placeholder="默认公开">
                <el-option
                  v-for="item in this.openOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
          <el-form-item label="文件类型" prop="fileType">
            <el-select v-model="form.fileType" placeholder="选择类型">
              <el-option
                v-for="item in this.dict.type.mc_file_type"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item >
              <template #label>
                <span style="color: red">*</span>
                <span>文件</span>
              </template>
              <el-upload
                class="upload-demo"
                action="#"
                :limit="1"
                :show-file-list="true"
                ref="upload_projectVideo"
                :auto-upload="false"
                :http-request="function (file) {return submitProjectVideo(file)}"
                list-type="picture"
              >
                <el-button size="small" type="primary">点击上传</el-button>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>

import { MessageBox } from 'element-ui'
import { getProductDataByCondition, delProductData} from '@/api/product/productInfoData'
import { uploadFuncAwait } from '@/utils/upload'
import { checkRole } from '@/utils/permission'

export default {
  name: "Document",
  props: {
    productTypeId: {
      type: String,
    },
  },
  dicts: ["mc_file_type"],
  created() {
    console.log(this.queryParams.productType)
    this.getList();
  },

  data() {
    return {
      loading:false,
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        title: [
          { required: true, message: "标题不能为空", trigger: "blur" },
        ],
        fileType: [
          { required: true, message: "请选择文件类型", trigger: "blur" },
        ],
      },
      openOptions: [{
        value: 1,
        label: '公开'
      }, {
        value: 0,
        label: '不公开'
      }],
      // 是否显示弹出层
      open: false,
      projectVideoFile:'',
      // 总条数
      total: 0,
      tableData: [],
      baseURL: process.env.VUE_APP_DOWNLOAD_API,
      // 显示搜索条件
      showSearch: true,
      allVersion:[],
      dateRange: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 50,
        productType: this.productTypeId,
        fileType: null,
        rangeTime: null,
        beginTime: null,
        endTime: null,
      }
    };
  },
  methods: {
    shouldShowEditButton(row) {
      return row.isOpen === 1 || checkRole(['admin', 'leader', 'staff']) ;
    },
    handleDownload(row){
      const a = document.createElement('a') // 创建一个<a></a>标签
      a.href = this.baseURL+ '/app/'+ row.url
      a.download = row.title + '.' + row.url.split('.').pop()
      a.style.display = 'none'           // 隐藏a标签
      document.body.appendChild(a)       // 将a标签追加到文档对象中
      a.click()                          // 模拟点击了a标签，会触发a标签的href的读取，浏览器就会自动下载了
      a.remove()
    },
    handleWatch(row){
      window.open(this.baseURL+ '/app/'+ row.url);
    },
    //删除视频教程
    handleDelete(row){
      MessageBox.confirm('此操作将永久删除该文件，是否继续？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delProductData({id:row.id}).then((res)=>{
          if(res.code == 200 ){
            this.$modal.msgSuccess("删除成功");
            this.getList()
          }
        })
      }).catch(() => {
        // 用户点击“取消”
        console.log("已取消");
      });
    },
    getList() {
      this.loading = true;
      getProductDataByCondition(this.addDateRange(this.queryParams, this.dateRange)).then((response) => {
        this.tableData = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(async valid => {
        if (valid) {
          let postUrlImg = '/productDataInfo/uploadProductData'
          this.$refs.upload_projectVideo.submit()
          if(this.projectVideoFile) {
            let formData = new FormData()
            formData.append('multipartFile', this.projectVideoFile)
            formData.append('title', this.form.title)
            formData.append('fileDesc', this.form.fileDesc)
            formData.append('fileType', this.form.fileType)
            formData.append('productType', this.productTypeId)
            formData.append('isOpen', this.form.isOpen)
            this.loading = true
            await uploadFuncAwait(postUrlImg, formData).then((res)=>{
              if(res.data.code == 200){
                this.$modal.msgSuccess("发布成功，等待审核，审核结果可在我的发布中查看");
                this.loading = false
                this.open = false
                this.getList()
              }else{
                this.$modal.msgError("发布失败: " + res.data.msg);
                this.loading = false
              }
            })
          }
        else{
            this.$modal.msgError("请选择上传文件");
          }
        }
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        fileDesc: '',
        isOpen: 1
      };
      this.projectVideoFile = ""
      this.resetForm("form");
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      this.reset();
      this.open = true;
      this.$refs.upload_projectVideo.clearFiles();
    },
    /**
     * 获取上传路径
     * @param file
     */
    submitProjectVideo(file) {
      this.projectVideoFile = file.file;
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
  },
};
</script>
<style scoped></style>
